//
//  HEOrderCommentViewController.m
//  HealthFamily
//
//  Created by 吴欧 on 2020/11/10.
//  Copyright © 2020 honglutec. All rights reserved.
//

#import "HEOrderCommentViewController.h"
#import "HECommentGoodsCell.h"
#import "HECommentTextViewCell.h"
#import "HECommentPhotoCell.h"
#import "HECommentScoreCell.h"
#import "HXPhotoPicker.h"
#import "HEOrderCommentRequest.h"

@interface HEOrderCommentViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) GDTableView *tableView;
@property (nonatomic, strong) NSMutableArray *sections;
@property (nonatomic, strong) GDFormModel *formModel;
@property (nonatomic, strong) NSMutableArray *formArrs;
@property (nonatomic, strong) NSMutableArray *imgsArr;

// 创建一个全局的group
@property (nonatomic, strong) dispatch_group_t group;

@end

@implementation HEOrderCommentViewController

- (NSMutableArray *)imgsArr {
    if (!_imgsArr) {
        _imgsArr = @[].mutableCopy;
    }
    return _imgsArr;
}

- (GDFormModel *)formModel {
    if (!_formModel) {
        _formModel = [[GDFormModel alloc] init];
        _formModel.proxyVC = self;
    }
    return _formModel;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"评价";
    
    [self.view addSubview:self.tableView];
    
    self.formModel.od_details = _model;
    
    // 总段
    _sections = [NSMutableArray array];
    _formArrs = [NSMutableArray array];
    
    for (HEOrderItemModel *item in _model.orderItemList) {
        [self initCell];
        
        GDFormModel *fmodel = [[GDFormModel alloc] init];
        fmodel.od_details = _model;
        fmodel.cm_score = 5;
        [_formArrs addObject:fmodel];
    }
    [self.tableView reloadData];

    [self initBottomView];
}

- (GDTableView *)tableView {
    if (!_tableView) {
        _tableView = [[GDTableView alloc] initWithFrame:CGRectMake(0, ZXNavBarHeight , KScreenWidth, KScreenHeight - ZXNavBarHeight - 60 - ZXSafeAreaBottom) style:UITableViewStylePlain];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.scrollsToTop = YES;
        _tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 0.01)];
        _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 0.01)];

        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.backgroundColor = CViewBgColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;

//        [_tableView registerClass:[HEMyOrderCell class] forCellReuseIdentifier: KHEMyOrderCell];
//        [_tableView registerClass:[HEMyOrderHeadCell class] forCellReuseIdentifier: @"HEMyOrderHeadCell"];
//        [_tableView registerClass:[HEMyOrderFooterCell class] forCellReuseIdentifier: @"HEMyOrderFooterCell"];

    }
    return _tableView;
}

- (void)initBottomView {
    UIView *bottomView = [UIView new];
    [self.view addSubview:bottomView];
    
    // 登录按钮
    QMUIFillButton *submitBtn = [[QMUIFillButton alloc] initWithFillType:QMUIFillButtonColorBlue];
    submitBtn.titleLabel.font = UIFontMake(15);
    [submitBtn setBackgroundColor:CNavBgColor];
    [submitBtn setTitle:@"提交" forState:UIControlStateNormal];
    [bottomView addSubview: submitBtn];
    [submitBtn addTarget:self action:@selector(submitBtn) forControlEvents:UIControlEventTouchUpInside];
  
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(self.view);
        make.height.mas_offset(60);
        make.bottom.offset(-ZXSafeAreaBottom);
    }];
    
    [submitBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(bottomView).mas_offset(20);
        make.right.equalTo(bottomView).mas_offset(-20);
        make.centerY.equalTo(bottomView);
        make.height.mas_offset(40);
    }];
}

- (void)submitBtn {
    
    BOOL hasAllValue = YES;
    for (int i = 0; i < _formArrs.count; i++) {
        GDFormModel *model = _formArrs[i];
        if ([DYTools isBlankString:model.cm_content]) {
            hasAllValue = NO;
        }
    }
    
    if (!hasAllValue) {
        [Dialog toastBottom:@"请输入评价或建议"];
        return;
    }
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue, ^{
        self.group = dispatch_group_create();
        
        // 上传图片
        for (int i = 0; i < self.formArrs.count; i++) {
            GDFormModel *model = self.formArrs[i];
            [self uploadImage:model];
        }
        
        //因上面请求中有加入dispatch_group_enter 和 dispatch_group_leave,所以真正等待上面线程执行完才执行这里面的请求
        dispatch_group_notify(self.group, queue, ^{
            [self createCommentRequest];
        });
    });
}

- (void)createCommentRequest {
    
    HEOrderCommentRequest *request = [HEOrderCommentRequest new];
    request.orderId = _model.id;
    NSMutableArray *items = @[].mutableCopy;
    for (int i = 0; i < _formArrs.count; i++) {
        GDFormModel *model = _formArrs[i];
        HEOrderItemModel *itemModel = _model.orderItemList[i];
    
        NSMutableDictionary *dict = @{}.mutableCopy;
        [dict setValue:[NSNumber numberWithInteger:model.cm_score] forKey:@"score"];
        [dict setValue:[NSNumber numberWithInteger:itemModel.productId] forKey:@"goodsId"];
        [dict setValue:model.cm_content forKey:@"textarea"];
        [dict setValue:model.cm_imgUrls forKey:@"images"];

        [items addObject:dict];
    }
    request.items = [items mj_JSONString];
    
    [WOAFNetWorkingHandle POSTWithBaseUrlByKeyValue:KServerUrl suffixUrl:Korderevaluate parameters:request success:^(id  _Nonnull responseObject) {
        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];
        if (response.success) {
            if (self.backBlock) {
                self.backBlock();
            }
            [self.navigationController popViewControllerAnimated:YES];
        }
    } failure:^(NSError * _Nonnull error) {
    }];
}

- (void)uploadImage:(GDFormModel *)model {
    dispatch_group_enter(_group);
    model.cm_imgUrls = @[].mutableCopy;

    if (!(model.cm_imgs.count > 0)) {
        dispatch_group_leave(self.group);
        return;
    }
    
    [WOAFNetWorkingHandle uploadImagesWithBaseURL:KServerUrl suffixUrl:Kbatch parameters:@{} name:nil images:model.cm_imgs fileNames:nil imageScale:0.8 imageType:nil progress:^(int64_t bytesProgress, int64_t totalBytesProgress) {
        

    } success:^(id  _Nonnull responseObject) {
        
        HEUploadResponse *response = [HEUploadResponse mj_objectWithKeyValues:responseObject];

        NSArray *array = [response.data.src componentsSeparatedByString:@","];
        for (NSString *url in array) {
            if (![DYTools isBlankString:url]) {
                [model.cm_imgUrls addObject:url];
            }
        }
        dispatch_group_leave(self.group);

    } failure:^(NSError * _Nonnull error) {
        dispatch_group_leave(self.group);
    }];
}

- (void)initCell {

    NSMutableArray *classArr = [NSMutableArray array];

    // 显示地址
    GDFiterCellModel *goodModel = [GDFiterCellModel new];
    goodModel.cellKlass = HECommentGoodsCell.class;
    goodModel.cellType = GDFiterCellTypeCommentGood;
    
    // 显示地址
    GDFiterCellModel *textModel = [GDFiterCellModel new];
    textModel.cellKlass = HECommentTextViewCell.class;
    textModel.cellType = GDFiterCellTypeCommentTextView;
    
    // 照片
    GDFiterCellModel *photoModel = [GDFiterCellModel new];
    photoModel.cellKlass = HECommentPhotoCell.class;
    photoModel.cellType = GDFiterCellTypeCommentPhoto;
    
    // 评分
    GDFiterCellModel *scoreModel = [GDFiterCellModel new];
    scoreModel.cellKlass = HECommentScoreCell.class;
    scoreModel.cellType = GDFiterCellTypeCommentScore;
     
 
    // 添加的时候注意顺序，暂未对顺序做处理
    classArr = @[goodModel, textModel, photoModel, scoreModel].mutableCopy;
    [self.tableView mc_registerCellByFiterModels:classArr];
    
    NSMutableArray *rows = @[].mutableCopy;
    for (GDFiterCellModel *model in classArr) {
        [rows addObject:model];
    }
    [_sections addObject:rows];
}

#pragma mark -



#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _sections.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSMutableArray *rows = _sections[section];
    return rows.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSMutableArray *rows = _sections[indexPath.section];
    GDFiterCellModel *fiterModel = rows[indexPath.row];
    GDFormModel *formModel = _formArrs[indexPath.section];
    
    UITableViewCell *cell = [_tableView mc_dequeueReusableCellWithClassType:fiterModel.cellKlass];
    fiterModel.fiterCellModelBlock((MCTableBaseCell *)cell, fiterModel, formModel, indexPath);
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSMutableArray *rows = _sections[indexPath.section];
    GDFiterCellModel *fiterModel = rows[indexPath.row];
    GDFormModel *formModel = _formArrs[indexPath.section];

    if (fiterModel.cellType == GDFiterCellTypeCommentPhoto) {
        return fiterModel.cellHeight;
    }
    
    return [tableView fd_heightForCellWithIdentifier: NSStringFromClass(fiterModel.cellKlass) cacheByIndexPath:indexPath configuration:^(MCTableBaseCell *cell) {
        [cell refreshContent:fiterModel formModel:formModel indexPath:indexPath];
    }];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
 
}


#pragma mark -

@end
